--
-- Author: yawei.zhu
-- Date: 2018-07-16 14:26:27
--
-- NewActivityDungeonsRoundPanel
--

local ClassRef = app.mvc.createPanelClass(...)

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.LionRoundStartNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)
    self:setNodeEventEnabled(true)
    self:refresh()

    self.beforeSnapshotHandler = EM:on("photo.openphotoview", function()
        if not cc:isDead(self) then
            self:hide()
        end
    end)

    self.afterSnapshotHandler = EM:on("photo.closephotoview", function()
        if not cc:isDead(self) then
            self:show()
        end
    end)
end

function ClassRef:onExit()
    EM:remove(self.beforeSnapshotHandler)
    EM:remove(self.afterSnapshotHandler)
end

function ClassRef:_tick(dt)
    if not self._data then return end

    local serverTime = app.session:getServerTime() or os.time()
    local remainedTime = math.ceil(self._time - serverTime)
    if remainedTime < 1 then remainedTime = 1 end
    self._ui.tips:setString( string.format(self._data.formatTime, remainedTime))
end

-- data 类型
-- title
-- time
-- formatTime
-- btnName
function ClassRef:refresh()
    if not self._data then return end
    local data = self._data

    self._ui.name:setString(data.title)
    display.setNodesMiddle(self._ui.Sprite, self._ui.dot, self._ui.name)

    -- 移除定时器
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end

    self._time = data.time
    if self._time <= 0 then
        self._ui.tips:setString(self._data.formatTime)
    else
        self:_tick()
        -- 添加定时器
        self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
    end

    local btn = self._ui.Button_start
    btn:getChildByName("name"):setString(data.btnName)

    btn:addClickEventListener(function()
        executeFunc(self._onOperate, "NewActivity_Round_Btn")
    end)
end

function ClassRef:onCloseView( cb )
    self._onCloseView = function()
        executeFunc(cb)
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

return ClassRef
